// pages/search/index.js
import { request } from "../../request/index";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    searchHot: [],
    doSearch: [],
    searchList: [],
    searchInput: "",
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 获取热门搜索
    request({ url: "/search/hot" }).then((result) => {
      let searchHot = result.data.result.hots;
      this.setData({
        searchHot,
      });
    });
    let doSearch = wx.getStorageSync("doSearch");
    this.setData({
      doSearch,
    });
  },
  // 监听搜索框键盘回车事件
  doSearch(e) {
    // 获取内存中的数据
    let doSearch = wx.getStorageSync("doSearch");
    let { value } = e.detail;
    // 判断内存中是否有值
    if (doSearch) {
      // 判断输入值是否在历史中存在
      let index = doSearch.findIndex((e) => e == value);
      // 将存在值删除
      if (index != -1) {
        doSearch.splice(index, 1);
      }
      // 将输入值添加到数组前
      doSearch.unshift(value);
      this.setData({
        doSearch,
      });
      // 放入内存
      wx.setStorageSync("doSearch", doSearch);
      return;
    }
    // 将doSearch变量改为数组
    doSearch = [];
    doSearch.unshift(value);
    this.setData({
      doSearch,
    });
    wx.setStorageSync("doSearch", doSearch);
  },
  // 搜索框双向绑定事件与搜索列表
  searchInput(e) {
    this.setData({
      searchInput: e.detail.value,
    });
    this.requests();
  },
  // 搜索历史点击事件
  handleSearch(e) {
    let { item } = e.currentTarget.dataset;
    this.setData({
      searchInput: item,
    });
    this.requests();
  },
  // 搜索请求
  requests() {
    let keywords = this.data.searchInput;
    if (keywords) {
      wx.request({
        url: "http://localhost:4000/search",
        data: { keywords },
        success: (result) => {
          let searchList = result.data.result.songs.slice(0, 6);
          this.setData({
            searchList,
          });
        },
      });
    }else{
      this.setData({
        searchList:[]
      });
    }
  },
  // 搜索框输入值清零
  handleInputDatele() {
    this.setData({
      searchInput: "",
    });
    this.requests();
  },
  // 删除搜索框指定数据
  handledeteleHistory(e) {
    let { index } = e.currentTarget.dataset;
    console.log(index);
    let { doSearch } = this.data;
    doSearch.splice(index, 1);
    this.setData({
      doSearch,
    });
    wx.setStorageSync("doSearch", doSearch);
  }
});
